<template>
    <div class="home-container">
        <Banner :banners="banners" :duration="1500"/>
        <NewsList :newsList="newsList"/>
        <Loading/>
    </div>
</template>

<script>
import PubSub from 'pubsub-js';

import Header from '../components/Header';
import Banner from '../components/Banner';
import Channels from '../components/news/Channels';
import NewsList from '../components/news/NewsList';
import Loading from '../components/Loading';

import { getBannersList, getNewsList } from '../services/NewsService';

export default {
    components: {
        Header,
        Banner,
        Channels,
        NewsList,
        Loading
    },
    data() {
        return {
            banners: [
                {
					image: require("../assets/banner/banner1.jpg"),
			        url: "/",
					title: "",
				},
				{
					image: require("../assets/banner/banner2.jpg"),
					url: "/",
					title: "",
				},
				{
					image: require("../assets/banner/banner3.jpg"),
					url: "/",
					title: "",
				}
            ],
            newsList: [],
            isLoading: false,
            page: 1,
            pageSize: 10,
            token: null
        }
    },
    computed: {
		channels() {
			return this.$store.state.channels.data;
		}
    },
    methods: {
        // 加载更多
        loadMore() {
            if (this.isLoading) return;
            this.isLoading = true;
            getNewsList(this.channels[0].action, this.page + 1, this.pageSize)
            .then(data => {
                data.newsList.forEach(item => this.newsList.push(item));
                this.page = data.page;
                this.isLoading = false;
            }).catch(() => this.isLoading = false);
        }
    },
    async created() {
        document.title = '首页';
        // 获取轮播图数据
        this.banners = await getBannersList();
        // 获取首页新闻数据
        let { newsList, page } = await getNewsList(this.channels[0].action);
        this.newsList = newsList;
        this.page = page;
        // 订阅页面滚动到底部的消息
        this.token = PubSub.subscribe('scrollBottom', () => {
            this.loadMore();
        });
    },
    destroyed() {
        PubSub.unsubscribe(this.token);
        this.token = null;
    }
}
</script>

<style scoped>
.home-container {
    width: 1140px;
    margin: 60px auto;
}
</style>